import { defineStore } from 'pinia'
import { ref} from 'vue'
import { constantRoutes } from '@/router'
import { getPermissionRoutesAPI } from '@/api/index'
import { compareRouters } from '@/utils/recursion-router'
import { useAuthStore } from './auth'

export const useRoutesStore = defineStore('routes', () => {
  // 后台返回的权限路由
  const routes = ref([])
  const setRoutes = async () => {
    const authStore = useAuthStore()
    try {
      // 获得后端权限路由
      const res = await getPermissionRoutesAPI(authStore.token)
      // 找到layout路由
      const layoutRoutes = constantRoutes.find(item => item.path === '/')
      // 得到符合权限的动态路由
      const permissionRoutes = compareRouters(res.data, layoutRoutes.children)
      routes.value.push(...permissionRoutes)
      // 用一个 Set 来记录已经出现过的 name
const seen = new Set();
const uniqueArr = routes.value.filter(item => {
  if (seen.has(item.name)) {
    return false;
  } else {
    seen.add(item.name);
    return true;
  }
});
routes.value = uniqueArr
      return true
    } catch (error) {
      console.log('error', error)
      return false
    }
  }
  const resetRoutes = () => {
    routes.value.splice(0)
    localStorage.removeItem('routes') // 删除持久化存储中的 routes 数据
  }
  return {
    routes,
    setRoutes,
    resetRoutes
  }
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'routes',
        storage: localStorage,
      },
    ],
  },
})
